package com.ccp.dev.qbdms.controller;

import com.alibaba.fastjson.JSONArray;
import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.util.PropertyUtil;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.poi.excel.reader.DataEntity;
import com.ccp.dev.core.poi.excel.reader.ExcelReader;
import com.ccp.dev.core.poi.excel.reader.FieldEntity;
import com.ccp.dev.core.poi.excel.reader.TableEntity;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.extend.service.ExtendSysOrgService;
import com.ccp.dev.extend.service.ExtendSysUserService;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.expimp.util.AbstractExpUtil;
import com.ccp.dev.qbdms.expimp.util.AuxiliaryUtil;
import com.ccp.dev.qbdms.model.WQbdAwardInformation;
import com.ccp.dev.qbdms.service.WQbdAwardInformationService;
import com.ccp.dev.qbdms.util.BaseUtil;
import com.ccp.dev.qbdms.util.ProjectUUIDUtils;
import com.ccp.dev.qbdms.util.StructureModifyUtil;
import com.ccp.dev.system.model.SysOrg;
import com.ccp.dev.system.model.SysUser;
import com.ccp.dev.system.service.SysUserService;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 获奖管理 信息操作处理控制器
 *
 * @author 王明亮
 * @date 2020-07-02 07:31:41
 */
@Controller
/**
 * 请将此名称添加到日志开关
 */
@Action(customModel = "获奖管理")
@RequestMapping("/qbdms/wQbdAwardInformation")
public class WQbdAwardInformationController extends SysBaseController {
    @Resource
    private WQbdAwardInformationService wQbdAwardInformationService;
    @Resource
    private ExtendSysOrgService extendSysOrgService;
    @Resource
    private SysUserService sysUserService;

    /**
     * 功能描述: 跳转到首页
     *
     * @return: java.lang.String
     * @auther: 王明亮
     * @date: 2020-07-02 07:31:41
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description = "跳转到获奖管理首页", exectype = "页面跳转日志")
    public String viewList(ModelMap modelMap) {
        // 当前系统等级
        BaseUtil.SystemLevel currentSystemLevel = BaseUtil.getCurrentSystemLevel();
        modelMap.put("currentSystemLevel", currentSystemLevel);
        // 当前登录用户id
        modelMap.put("currentUserId", ContextUtil.getCurrentUserId());
        return "wQbdAwardInformation/list";
    }

    /**
     * 功能描述: 附带检索条件的分页查询
     *
     * @param: [request] http请求
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-07-02 07:31:41
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description = "附带检索条件的分页查询获奖管理", detail = "查询数据信息<#if success>成功<#else></#if>")
    public Object list(HttpServletRequest request) throws IllegalAccessException {
        QueryFilter queryFilter = new QueryFilter(request, true);
        // 默认按照评定时间倒序排列,评定时间相同的情况下按创建时间倒序排列
        if (StringUtil.isEmpty(queryFilter.get("orderField"))) {
            queryFilter.addFilter("orderField", "award_date");
            queryFilter.addFilter("orderSeq", "desc");
            queryFilter.addFilter("orderField1", "createtime");
            queryFilter.addFilter("orderSeq1", "desc");
        }
        ZhiLiangConst.addQueryFilter(queryFilter);
        //分页数据
        List<WQbdAwardInformation> pageDatas = wQbdAwardInformationService.queryList(queryFilter);
        // 密级、上报状态、数据来源单位显示中文
        ZhiLiangConst.showName(pageDatas);
        // 添加编辑按钮权限控制
        ZhiLiangConst.isDataAllowEdit(pageDatas, false);
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return success(pageDatas, queryFilter.getPageBean().getTotalCount());
    }


    /**
     * 功能描述: 跳转到新增页面
     *
     * @return: java.lang.String
     * @auther: 王明亮
     * @date: 2020-07-02 07:31:41
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description = "跳转到获奖管理新增页面", exectype = "页面跳转日志")
    public String viewAdd(HttpServletRequest request, ModelMap modelMap) {
        String id = RequestUtil.getString(request, "id");
        modelMap.put("id", id);
        String orgName = ContextUtil.getCurrentOrg().getOrgName();
        modelMap.put("orgName", orgName);
        String code = ((SysOrg) ContextUtil.getCurrentOrg()).getCode();
        modelMap.put("code", code);
        // 上传附件类型相关
        String fileManagementUploadType = PropertyUtil.getByAlias("fileManagementUploadType", "");
        modelMap.put("fileManagementUploadType", fileManagementUploadType);
        String wjszsdsxlx = PropertyUtil.getByAlias("wjszsdsxlx", "");
        modelMap.put("wjszsdsxlx", wjszsdsxlx);
        return "wQbdAwardInformation/add";
    }

    /**
     * 功能描述:  数据保存通用方法
     *
     * @param: wQbdAwardInformation 保存的对象
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-07-02 07:31:41
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description = "保存获奖管理数据", detail = "<#if isAdd>新增<#else>编辑</#if>获奖管理数据<#if success>成功<#else>失败</#if><#if StringUtil.isNotEmpty(modifyInfo)>${modifyInfo}</#if>")
    public Object save(@RequestBody WQbdAwardInformation wQbdAwardInformation) {
        String id = wQbdAwardInformation.getId();
        int result;
        // 由于人员选择器没有返回组织code，因此在此单独处理。获取获奖人所在租户code
        if (StringUtil.isNotEmpty(wQbdAwardInformation.getWorkDept())) {
            String account = wQbdAwardInformation.getAwardPersonId();
            SysUser user = sysUserService.getByAccount(account);
            SysOrg sysOrg = extendSysOrgService.getTenOrg(user.getUserId());
            wQbdAwardInformation.setWorkDeptCode(sysOrg.getCode());
        }
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("isAdd", true);
            //新增操作
            //新增数据前生成随机Id
            wQbdAwardInformation.setId(ProjectUUIDUtils.getUUIDFor32());
            ZhiLiangConst.addCommonFields(wQbdAwardInformation);
            //上报状态
            BaseUtil.SystemLevel currentSystemLevel = BaseUtil.getCurrentSystemLevel();
            if (BaseUtil.SystemLevel.GROUPLEVEL.equals(currentSystemLevel)) {
                wQbdAwardInformation.setReportStatus(ZhiLiangConst.GROUP_ADD);
            } else if (BaseUtil.SystemLevel.HOSPITALLEVEL.equals(currentSystemLevel)) {
                wQbdAwardInformation.setReportStatus(ZhiLiangConst.REPORT_STATUS_GROUPTOBEREPORTED);
            } else if (BaseUtil.SystemLevel.PLANTLEVEL.equals(currentSystemLevel)) {
                wQbdAwardInformation.setReportStatus(ZhiLiangConst.getDataInitStatusToHospital());
            }
            result = wQbdAwardInformationService.add(wQbdAwardInformation);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            //修改操作
            ZhiLiangConst.updateCommonFields(wQbdAwardInformation);
            result = wQbdAwardInformationService.update(wQbdAwardInformation);
            SysAuditThreadLocalHolder.putParamerter("modifyInfo", StructureModifyUtil.getModifyInfo(wQbdAwardInformationService.getOneById(id), wQbdAwardInformation));
        }
        if (result > 0) {
            SysAuditThreadLocalHolder.putParamerter("success", true);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
        }
        return result > 0 ? getResultDataSuccess("save.success") : getResultDataError("save.failure");
    }

    /**
     * 功能描述: 跳转到详情页面
     *
     * @return: java.lang.String
     * @auther: 王明亮
     * @date: 2020-07-02 07:31:41
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/particulars")
    @Action(description = "跳转到获奖管理详情页面", exectype = "页面跳转日志")
    public String viewParticulars(HttpServletRequest request, ModelMap modelMap) {
        String id = RequestUtil.getString(request, "id");
        modelMap.put("id", id);
        String isClose = RequestUtil.getString(request, "isClose");
        modelMap.put("isClose", isClose);
        return "wQbdAwardInformation/particulars";
    }

    /**
     * 功能描述: 根据主键id获取一条数据的通用查询方法
     *
     * @param: id 参数对象必须是"id"
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-07-02 07:31:41
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    @Action(description = "根据主键id查询获奖管理的一条数据", detail = "根据主键id查询获奖管理的数据<#if success>成功<#else>失败</#if>")
    public Object get(@RequestParam("id") String id) {
        WQbdAwardInformation wQbdAwardInformation = wQbdAwardInformationService.getOneById(id);
        if (null == wQbdAwardInformation) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("get.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("get.success", wQbdAwardInformation);
    }

    /**
     * 功能描述: 根据主键ID删除数据的通用删除方法
     *
     * @param: id 参数名称必须是"id"
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-07-02 07:31:41
     */
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description = "根据主键ID删除获奖管理数据", exectype = "删除日志", detail = "删除数据信息<#if success>成功<#else>失败</#if>")
    public Object delete(@RequestParam("id") String id) {
        String userId = ContextUtil.getCurrentUserId();
        String[] ids = id.split(",");
        for (String key : ids) {
            WQbdAwardInformation wQbdAwardInformation = wQbdAwardInformationService.getOneById(key);
            if (!userId.equals(wQbdAwardInformation.getCreateBy())) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，只能删除自己创建的数据！");
            }
              /* 注:原来的逻辑是允许删除待上报、待报集团和集团新增的数据的数据，原想三级单位可以删除待上报、院级单位可以删除待报集团、集团可以删除集团新增的数据，可是没加系统等级限制
                  这就造成：三级单位上报到院后，（集中部署的情况下）这条数据的上报状态变成了待报集团，而待报集团是允许删除的，因而三级单位能够删除这条数据。
                  修改添加系统等级限制
             */
            if (BaseUtil.isGroupLevel()) {
                if (!Objects.isNull(wQbdAwardInformation.getReportStatus()) && !ZhiLiangConst.GROUP_ADD.equals(wQbdAwardInformation.getReportStatus())) {
                    return fail("删除失败，集团只允许删除集团新增的数据");
                }
            } else if (BaseUtil.isHospitalLevel()) {
                if (!Objects.isNull(wQbdAwardInformation.getReportStatus()) && !ZhiLiangConst.REPORT_STATUS_GROUPTOBEREPORTED.equals(wQbdAwardInformation.getReportStatus())) {
                    return fail("删除失败，院级单位只允许删除待报集团的数据");
                }
            } else if (BaseUtil.isPlantLevel()) {
                if (!Objects.isNull(wQbdAwardInformation.getReportStatus()) && !ZhiLiangConst.REPORT_STATUS_TEMP_TOBEREPORTED.equals(wQbdAwardInformation.getReportStatus())) {
                    return fail("删除失败，三级单位只允许删除待上报的数据");
                }
            }
            /*if (Objects.nonNull(wQbdAwardInformation.getReportStatus()) && !ZhiLiangConst.REPORT_STATUS_TEMP_TOBEREPORTED.equals(wQbdAwardInformation.getReportStatus()) && !ZhiLiangConst.REPORT_STATUS_GROUPTOBEREPORTED.equals(wQbdAwardInformation.getReportStatus()) && !ZhiLiangConst.GROUP_ADD.equals(wQbdAwardInformation.getReportStatus())) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，只允许删除待上报、待报集团和集团新增的数据");
            }*/
        }
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return fail("delete.failure.message");
        }
        int result = wQbdAwardInformationService.delByIdArray(id.split(","));
        if (result > 0) {
            SysAuditThreadLocalHolder.putParamerter("success", true);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
        }
        return result > 0 ? getResultDataSuccess("delete.success") : getResultDataError("delete.failure");
    }

    /**
     * 功能描述: 跳转到导入页面
     *
     * @return: java.lang.String
     * @auther: hw
     * @date: 2019-12-25 19:21:40
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/import")
    @Action(description = "跳转到获奖管理导入页面", exectype = "页面跳转日志")
    public String viewImport() {
        return "wQbdAwardInformation/import";
    }

    /**
     * 功能描述: 跳转到导出选择字段页面
     *
     * @param request
     * @param modelMap
     * @return
     * @throws Exception
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/export")
    @Action(description = "跳转到获奖管理导出选择字段页面", exectype = "页面跳转日志")
    public String export(HttpServletRequest request, ModelMap modelMap) throws Exception {
        com.alibaba.fastjson.JSONObject jsonObject = AuxiliaryUtil.resolverModel(WQbdAwardInformation.class);
        modelMap.put("tableInfo", jsonObject.toString());
        return "expImp/add";
    }

    /**
     * 功能描述: 导出获奖管理数据信息
     *
     * @param: [request] http请求
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-07-02 07:31:41
     */
    @RequestMapping("/exportData")
    @Action(description = "导出获奖管理数据信息", detail = "导出获奖管理数据信息<#if success>成功<#else></#if>")
    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception {
        SysAuditThreadLocalHolder.putParamerter("success", false);
        String[] id = RequestUtil.getStringAryByStr(request, "id");
        QueryFilter queryFilter = new QueryFilter(request, false);
        // 默认按照评定时间倒序排列,评定时间相同的情况下按创建时间倒序排列
        queryFilter.addFilter("orderField", "award_date");
        queryFilter.addFilter("orderSeq", "desc");
        queryFilter.addFilter("orderField1", "createtime");
        queryFilter.addFilter("orderSeq1", "desc");
        JSONArray dataArray = ZhiLiangConst.exportAddConditions(queryFilter, id);
        List<WQbdAwardInformation> wQbdAwardInformations = this.wQbdAwardInformationService.queryAll(queryFilter);
        if (wQbdAwardInformations.isEmpty()) {
            wQbdAwardInformations.add(new WQbdAwardInformation());
        }
        new AbstractExpUtil() {
            @Override
            public String customAnalysis(String fieldName, String fieldValue) {
                return null;
            }
        }.executeExport(request, response, wQbdAwardInformations, dataArray, AbstractExpUtil.ExpStyle.MANY_SHEET);
        SysAuditThreadLocalHolder.putParamerter("success", true);
    }

    /**
     * 导入资源文件
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/importData")
    public void importData(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception {
        MultipartFile multipartFile = request.getFile("file");
        PrintWriter writer = response.getWriter();
        try {
            String fileName = multipartFile.getOriginalFilename();
            String extName = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            //读取excel文件，并获取每行的数据
            ExcelReader excelReader = new ExcelReader();
            TableEntity excelEntity = excelReader.readFile(multipartFile.getInputStream());
            List<DataEntity> rowDataEntityList = excelEntity.getDataEntityList();

            List<WQbdAwardInformation> listToInsert = new ArrayList<>();
            for (DataEntity dataEntity : rowDataEntityList) {
                //获取每列的数据
                List<FieldEntity> fieldEntityList = dataEntity.getFieldEntityList();
                WQbdAwardInformation dataToInsert = new WQbdAwardInformation();
                int i = 0;
                //根据列的顺序，给相应的对象赋值
                for (FieldEntity fieldEntity : fieldEntityList) {
                    //if(i==0){
                    //dataToInsert.setName(fieldEntity.getValue());
                    //}
                    i++;
                }
                dataToInsert.setId(UUIDUtils.getUUIDFor32());
                listToInsert.add(dataToInsert);
            }
            wQbdAwardInformationService.addList(listToInsert);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            JSONObject json = JSONObject.fromObject(getResultDataSuccess("operation.success"));
            writer.print(new String(json.toString().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            JSONObject json = JSONObject.fromObject(getResultDataError("operation.failure"));
            writer.print(new String(json.toString().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
        }
    }

    /**
     * 查询上报的信息
     *
     * @param id        业务数据主键
     * @param tableName 业务表名
     * @return
     */
    @RequestMapping("/reportList")
    @ResponseBody
    public Object reportList(@RequestParam("id") String id, @RequestParam("tableName") String tableName) throws IllegalAccessException {
        //业务数据
        List<WQbdAwardInformation> reportList = wQbdAwardInformationService.reportList(id, tableName);
        ZhiLiangConst.showName(reportList);
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("options.success", reportList);
    }

}
